const { User, UserType, Department } = require('../../database/index')
const jwt = require('jsonwebtoken')
const { getExecutedSql } = require('../../logger');
// 导出
module.exports = async (req, res) =>
{
    // 接收客户端传递过来的账号密码
    const { username, password } = req.body
    console.log(username, password)

    const findUser = await User.findOne({
        where: { username },
        include: [{
            model: UserType,
            attributes: ['UserTypeName']
        },
        {
            model: Department,
            attributes: ['DepartmentName']
        }],
        attributes: ['UserTypeID', 'UserID', 'UserName', 'Password', 'FullName', 'Email', 'PhoneNumber', 'Avatar', 'Sex', 'Introduction']
    })
    const executedSql = getExecutedSql()
    // 访问权限字段
    // 判断
    if (!findUser) {
        res.status(400).send({
            data: null,
            meta: {
                msg: "用户名不存在",
                status: 400
            },
            sql: executedSql
        })
        return
    }
    // 判断账号和密码是否正确
    if (username != findUser.UserName || password != findUser.Password) {
        res.status(400).send({
            data: null,
            meta: {
                msg: "用户名或者密码不正确",
                status: 400
            },
            sql: executedSql

        })
        return
    }
    // 创建一个有效载荷对象
    const payload = {
        username: findUser.UserName,
        exp: Math.floor(Date.now() / 1000) + (60 * 60), // 设置为当前时间 + 1 小时
    };
    // 登录成功 创建token
    const token = jwt.sign(payload, 'chengfeng')
    const userData = {
        userID: findUser.UserID,
        userName: findUser.UserName,
        fullName: findUser.FullName,
        password: findUser.Password,
        email: findUser.Email,
        phoneNumber: findUser.PhoneNumber,
        userType: findUser.UserType.UserTypeName,
        departmentName: findUser.Department.DepartmentName,
        sex: findUser.Sex,
        avatarUrl: findUser.Avatar,
        introduction: findUser.Introduction,
    }
    res.status(200).send({
        data: userData,
        token: token,
        meta: {
            msg: "登录成功",
            status: 200
        },
        sql: executedSql
    })
}